import router, { constantRoutes, dashboard } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { post } from "@/api/request";
import { isURL } from "@/utils/validate";
import { userApi } from "@/api/user";

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const _import = require('@/router/import-' + process.env.NODE_ENV)
const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {



  /**
   * 判断当前路由类型, global: 全局路由, main: 主入口路由
   * @param {*} route 当前路由
   */


  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {

      try {

        // get user info
        await store.dispatch('user/getInfo')


        if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, constantRoutes) === 'global') {
          next()
        } else {
          userApi.nav().then(data=> {
            if (data && data.code === 20000) {
              fnAddDynamicMenuRoutes(data.menuList)
              router.options.isAddDynamicMenuRoutes = true
              sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
              sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
              NProgress.done()
              next({ ...to, replace: true })
            } else {
              sessionStorage.setItem('menuList', '[]')
              sessionStorage.setItem('permissions', '[]')
              NProgress.done()
              next()
            }
          }).catch((e) => {
            console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
            store.dispatch('user/resetToken')
            router.push({ name: 'login' })
          })
        }







      } catch (error) {
        // remove token and go to login page to re-login
        await store.dispatch('user/resetToken')
        Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }

    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }


})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
function fnCurrentRouteType(route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      var route = {
        path: menuList[i].url.replaceAll('/', '-'),
        component: null,
        name: menuList[i].url.replaceAll('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`${menuList[i].url}`) || null
        } catch (e) {
          console.log(e)
        }
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    dashboard.name = 'main-dynamic'
    dashboard.children = routes
    router.addRoutes([
      dashboard,
      { path: '*', redirect: { path: '404' } }
    ])
    // sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(dashboard.children || '[]'))
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    // console.log(dashboard.children)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}
